package com.hadoop.fs;

import java.io.FileNotFoundException;
import java.io.OutputStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.hamcrest.Matchers;

public class ShowFileStatusTest {

	private MiniDFSCluster cluster;
	private FileSystem fs;

	@Before
	public void setUp() throws Exception {
		Configuration conf = new Configuration();
//		conf.set("hbase.zookeeper.quorum", "hadoop.main");// 连接到远程服务上
//		conf.set("dfs.name.dir", "/home/conkeyn/hadoop_var/name");
		if (System.getProperty("test.build.data") == null) {
			System.setProperty("test.build.data", "/tmp");
		}
		cluster = new MiniDFSCluster(conf, 1, null);
		fs = cluster.getFileSystem();
		OutputStream out = fs.create(new Path("/dir/file"));
		out.write("测试内容".getBytes("UTF-8"));
		out.close();
	}

	@After
	public void tearDown() throws Exception {
		if (fs != null) {
			fs.close();
		}
		if (cluster != null) {
			cluster.shutdown();
		}
	}

	@Test(expected = FileNotFoundException.class)
	public void throwsFileNotFoundNonExistenFile() throws Exception {
		fs.getFileStatus(new Path("no-such-file"));
	}
	@Test
	public void fileStatusForFile() throws Exception {
		Path p = new Path("/dir/file");
		FileStatus stat = fs.getFileStatus(p);
		Assert.assertThat(stat.getPath().toUri().getPath(), Matchers.is("/dir/file"));
		Assert.assertThat(stat.isDir(), Matchers.is(false));
		Assert.assertThat(stat.getLen(), Matchers.is(12L));
		Assert.assertThat(stat.getModificationTime(), Matchers.is(Matchers.lessThanOrEqualTo(System.currentTimeMillis())));
		Assert.assertThat(stat.getReplication(), Matchers.is((short)1));
		Assert.assertThat(stat.getBlockSize(), Matchers.is(64*1024*1024l));//块大小是否为64M
		Assert.assertThat(stat.getOwner(), Matchers.is("conkeyn"));
		Assert.assertThat(stat.getGroup(), Matchers.is("conkeyn"));
		Assert.assertThat(stat.getPermission().toString(), Matchers.is("rw-r--r--"));
	}
	@Test
	public void fileStatusForDir() throws Exception {
		Path p = new Path("/dir");
		FileStatus stat = fs.getFileStatus(p);
		Assert.assertThat(stat.getPath().toUri().getPath(), Matchers.is("/dir"));
		Assert.assertThat(stat.isDir(), Matchers.is(true));
		Assert.assertThat(stat.getLen(), Matchers.is(0L));
		Assert.assertThat(stat.getModificationTime(), Matchers.is(Matchers.lessThanOrEqualTo(System.currentTimeMillis())));
		Assert.assertThat(stat.getReplication(), Matchers.is((short)0));
		Assert.assertThat(stat.getBlockSize(), Matchers.is(0l));//块大小是否为64M
		Assert.assertThat(stat.getOwner(), Matchers.is("conkeyn"));
		Assert.assertThat(stat.getGroup(), Matchers.is("conkeyn"));
		Assert.assertThat(stat.getPermission().toString(), Matchers.is("rwxr-xr-x"));
	}
}
